package com.uxsino.rule.nms.validate;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.uxsino.rule.model.StringCompareWay;

import lombok.Data;
import lombok.EqualsAndHashCode;

@Data
@EqualsAndHashCode(callSuper = false)
public class StringValidator extends BaseValidate {
    private static Logger logger = LoggerFactory.getLogger(StringValidator.class);

    private StringCompareWay compareWay;

    private String value;

    private String target;

    public StringValidator(StringCompareWay compareWay, String value, String target) {
        this.compareWay = compareWay;
        this.value = value;
        this.target = target;
    }

    @Override
    public boolean validate() {
        if (compareWay == null) {
            logger.error("String validate -> CompareWay is null!");
            return false;
        }
        if (value == null) {
            logger.error("String validate -> Value is null!");
            return false;
        }
        if (target == null) {
            logger.error("String validate -> Target is null!");
            return false;
        }
        switch (compareWay) {
        case CONTAINS:
            return containsAll(value, target);
        // return value.contains(target);
        case NOT_CONTAINS:
            return !containsAny(value, target);
        // return !value.contains(target);
        case START_WITH:
            return value.startsWith(target);
        case END_WITH:
            return value.endsWith(target);
        case EQUALS:
            return equalsAny(value, target);
        // return value.equals(target);
        case NOT_EQUALS:
            return !equalsAny(value, target);
        // return !value.equals(target);
        /* case regexper:
        if (regexper(value, target)) {
            msg.setRange(CompareWay.regexper.getText() + "[" + target + "]");
        } else {
            status = not_hit;
        }
        break;*/
        default:
            return false;
        }
    }

    private static boolean equalsAny(String value, String target) {
        String[] targets = target.split(",");
        for (String t : targets) {
            if (value.equals(t)) {
                return true;
            }
        }
        return false;
    }

    private static boolean containsAll(String value, String target) {
        String[] targets = target.split(",");
        for (String t : targets) {
            if (!value.contains(t)) {
                return false;
            }
        }
        return true;
    }

    private static boolean containsAny(String value, String target) {
        String[] targets = target.split(",");
        for (String t : targets) {
            if (value.contains(t)) {
                return true;
            }
        }
        return false;
    }
}
